import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken,setUserId,setWeUserId,setInsuranceType,getInsuranceType,removeUserId,removeInsuranceType} from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    companyName: '',
    avatar: '',
    roles: [],
    permissions: [],
    userId:null,
    weUserId: null,
    deptName:null,
    insuranceType:getInsuranceType(),
    allInsuranceType: [],
    userName: null,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
      setUserId(userId)
    },
    SET_WEUSERID: (state, weUserId) => {
      state.weUserId = weUserId
      setWeUserId(weUserId)
    },
    SET_DEPTNAME: (state, deptName) => {
      state.deptName = deptName
    },
    SET_INSURANCETYPE:(state, insuranceType) => {
      state.insuranceType = insuranceType
      setInsuranceType(insuranceType)
    },
    SET_ALL_INSURANCETYPE:(state, insuranceType) => {
      state.allInsuranceType = insuranceType
    },
    SET_USERNAME: (state, userName) => {
      state.userName = userName
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then((res) => {
            setToken(res.data.access_token)
            commit('SET_TOKEN', res.data.access_token)
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 获取用户信息
    // GetInfo({ commit, state }) {
    //   return new Promise((resolve, reject) => {
    //     getInfo(state.token)
    //       .then((res) => {
    //         const user = res.user
    //         const avatar =
    //           user.avatar == ''
    //             ? require('@/assets/image/profile.jpg'):user.avatar
    //       : window.globalConfig.BASE_API + user.avatar
    //         if (res.roles && res.roles.length > 0) {
    //           // 验证返回的roles是否是一个非空数组
    //           commit('SET_ROLES', res.roles)
    //           commit('SET_PERMISSIONS', res.permissions)
    //         } else {
    //           commit('SET_ROLES', ['ROLE_DEFAULT'])
    //         }
    //         commit('SET_NAME', user.userName)
    //         commit('SET_AVATAR', avatar)
    //         commit('SET_USERID', user.userId)
    //         commit('SET_DEPTNAME', user.dept.deptName)
    //         commit('SET_USERNAME', user.userName)
    //         const insuranceType = user.insuranceType.split(',')
    //         commit('SET_ALL_INSURANCETYPE', insuranceType)
    //
    //         if(!getInsuranceType()&&user.insuranceType){
    //           const insuranceType=user.insuranceType.split(',')
    //           console.log(insuranceType,'insuranceType');
    //           commit('SET_INSURANCETYPE', insuranceType[0])
    //         }
    //         state.companyName = user.companyName
    //         resolve(res)
    //       })
    //       .catch((error) => {
    //         reject(error)
    //       })
    //   })
    // },

    async GetInfo({ commit, state }) {
      try {
        const res = await getInfo(state.token)
        const insuranceType = res.user.insuranceType.split(',')
        commit('SET_ROLES', res.roles || ['ROLE_DEFAULT'])
        commit('SET_PERMISSIONS', res.permissions || [])
        commit('SET_NAME', res.user.userName)
        commit('SET_AVATAR', res.avatar || require('@/assets/image/profile.jpg'))
        commit('SET_USERID', res.user.userId)
        commit('SET_WEUSERID', res.user.weUserId)
        commit('SET_DEPTNAME', res.user.dept.deptName)
        commit('SET_USERNAME', res.user.userName)
        commit('SET_ALL_INSURANCETYPE', insuranceType)

        if (!getInsuranceType() && res.user.insuranceType) {
          const insuranceType = res.user.insuranceType.split(',')
          console.log(insuranceType, 'insuranceType');
          commit('SET_INSURANCETYPE', insuranceType[0])
        }

        state.companyName = res.user.companyName
        return res
      } catch (error) {
        console.error('获取用户信息失败', error)
        throw error
      }
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            commit('SET_PERMISSIONS', [])
            commit('SET_USERID', '')
            commit('SET_WEUSERID', '')
            commit('SET_DEPTNAME', '')
            commit('SET_USERNAME', '')
            removeUserId()
            removeInsuranceType()
            removeToken()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
